<template>
  <div class="upload-container">
    <!-- 上传按钮 -->
    <div class="upload-header">
      <el-upload
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleFileChange"
      >
        <el-button type="primary">Choose File</el-button>
      </el-upload>
    </div>

    <!-- 文件列表表格 -->
    <el-table
      :data="paginatedFiles"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="频道序号" prop="channelId"></el-table-column>
      <el-table-column label="名字" prop="channel"></el-table-column>
      <el-table-column label="地址" prop="url"></el-table-column>
      <el-table-column label="防盗密码" prop="password"></el-table-column>
      <el-table-column label="分类" prop="category"></el-table-column>
    </el-table>

    <!-- 底部操作区 -->
    <div class="footer-container">
      <!-- 分页控制 -->
      <div class="pagination-control">
        <el-button @click="prevPage" :disabled="currentPage === 1">上一页</el-button>
        <span>第 {{ currentPage }} 页</span>
        <el-button @click="nextPage" :disabled="currentPage >= totalPages">下一页</el-button>
        <span>跳转到 <el-input-number v-model="inputPage" :min="1" :max="totalPages"></el-input-number> 页</span>
      </div>

      <!-- 直播分类多选框 -->
      <el-form>
        <el-form-item label="直播分类" prop="categories">
          <el-checkbox-group v-model="selectedCategories">
            <el-checkbox
              v-for="item in categories"
              :label="item"
              :key="item.typeId"
            >
              {{ item.typeName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 新分类输入和按钮 -->
        <div class="category-edit">
          <el-button type="primary" @click="updateSelectedCategories">编辑选中</el-button>
        </div>
      </el-form>

      <!-- 导入方式 -->
      <div class="import-mode">
        <el-radio-group v-model="importMode">
          <el-radio label="cover">覆盖原有内容</el-radio>
          <el-radio label="append">继续添加内容</el-radio>
        </el-radio-group>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button @click="handleCancel">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {listLiveType} from "@/api/media/live/type/list";
import {importLive} from "@/api/media/live/list";

export default {
  data() {
    return {
      // 文件相关
      allFiles: [],
      selectedFiles: [],

      // 分页相关
      currentPage: 1,
      pageSize: 100,
      inputPage: 1,

      // 分类相关
      categories: [], // 所有分类
      selectedCategories: [], // 用于存储用户选择的分类

      // 导入模式
      importMode: 'cover'
    };
  },
  computed: {
    // 分页后的文件列表
    paginatedFiles() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.allFiles.slice(start, end);
    },
    // 总页数
    totalPages() {
      return Math.ceil(this.allFiles.length / this.pageSize);
    }
  },
  watch: {
    inputPage(val) {
      this.currentPage = Math.min(Math.max(1, val), this.totalPages);
    }
  },
  created() {
    this.getList();
  },
  methods: {

    // 更新选中文件的分类
    updateSelectedCategories() {

      this.selectedFiles.forEach(file => {
        file.category = this.selectedCategories.map(item=>item.typeName).join(',');
        file.categoryIds=this.selectedCategories.map(item=>item.typeId).join(',');
      });
      // 更新文件列表
      this.allFiles = [...this.allFiles];
    },

    getList() {
      this.loading = true;
      listLiveType().then(response => {
        this.categories = response.rows;
        this.total = response.total;
      });
      this.loading = false;
    },
    handleFileChange(file) {
      this.allFiles = [];

      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target.result;
        const lines = content.split('\n');
        lines.forEach((line, index) => {
          if (line.trim() !== '') {
            const [channelId,channel, url, password,category] = line.split(',');
            this.allFiles.push({
              channelId: channelId ? channelId.trim() : '',
              channel: channel ? channel.trim() : '',
              url: url ? url.trim() : '',
              password: password ? password.trim() : '',
              category: category ? category.trim() : ''
            });
          }
        });
      };
      reader.readAsText(file.raw);
    },
    // 选择改变
    handleSelectionChange(selection) {
      this.selectedFiles = selection;
    },
    // 分页操作
    prevPage() {
      this.currentPage = Math.max(1, this.currentPage - 1);
    },
    nextPage() {
      this.currentPage = Math.min(this.totalPages, this.currentPage + 1);
    },
    // 导入操作
    handleImport() {
      if (this.selectedFiles.length) {
        const invalidRows = this.selectedFiles.filter(file => !file.category);

        if (invalidRows.length > 0) {
          const missingCategoryIds = invalidRows.map(row => row.channelId);

          const missingIdsText = missingCategoryIds.join(", ");
          this.$modal.alertWarning(`以下频道没有选择分类，请检查后再导入：\n${missingIdsText}`);
          return;
        }

        this.$modal.confirm("是否确认导入？").then(() => {
          importLive(this.importMode, this.selectedFiles).then(() => {
            this.$router.go(-1);
          }).catch(error => {
          });
        }).catch(() => {
        });
      } else {
        this.$modal.alertWarning("请选择导入数据");
      }
    },

    // 返回操作
    handleCancel() {
      this.$router.go(-1);
    }
  }
};
</script>

<style scoped lang="scss">
.upload-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .upload-header {
    margin-bottom: 20px;
  }

  .footer-container {
    margin-top: 20px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;

    .pagination-control {
      display: flex;
      align-items: center;
      gap: 15px;
      margin-bottom: 15px;
    }

    .category-filter {
      margin: 15px 0;
      display: flex;
      gap: 20px;
    }

    .import-mode {
      margin: 15px 0;
    }

    .action-buttons {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
